package com.xxl.sso.server.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.sso.server.core.model.UserInfo;
import com.xxl.sso.server.core.result.ReturnT;
import com.xxl.sso.server.mapper.UserMapper;
import com.xxl.sso.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    // private static List<UserInfo> mockUserList = new ArrayList<>();
    // static {
    //     for (int i = 0; i <5; i++) {
    //         UserInfo userInfo = new UserInfo();
    //         userInfo.setUserid(1000+i);
    //         userInfo.setUsername("user" + (i>0?String.valueOf(i):""));
    //         userInfo.setPassword("123456");
    //         mockUserList.add(userInfo);
    //     }
    // }

    @Override
    public ReturnT<UserInfo> findUser(String username, String password) {

        if (username==null || username.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "Please input username.");
        }
        if (password==null || password.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "Please input password.");
        }

        // mock user
        // for (UserInfo mockUser: mockUserList) {
        //     if (mockUser.getUsername().equals(username) && mockUser.getPassword().equals(password)) {
        //         return new ReturnT<UserInfo>(mockUser);
        //     }
        // }

        //1. 根据用户名从数据库查询用户
        UserInfo userInfo = userMapper.selectOne(new QueryWrapper<UserInfo>().eq("username", username));
        if(!Objects.isNull(userInfo)){
            String dbPwd = userInfo.getPassword();
            //1.1  将用户输入的密码进行加密
            String pwd = SecureUtil.md5(password);
            //1.2 比较密码是否相等
            if(pwd.equals(dbPwd)){
                return new ReturnT<>(userInfo);
            }
        }
        return new ReturnT<>(ReturnT.FAIL_CODE, "用户名或密码无效.");
    }


}
